package com.zhaodui.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.util.ResourceUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 图片上传
 * @Author luoyixin
 * @E-mail 765710732@qq.com
 * @Date 2017/11/28 15:49.
 */

@Controller
@RequestMapping("/upload")
public class UploadController {

    /**
     * 图片上传
     * @param imgfile
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(params ="photo")
    public AjaxJson fileUploadPicture(String imgfile, HttpServletRequest request)  throws IOException{
        String message = "";
        AjaxJson j = new AjaxJson();
        String savaPath= ResourceUtil.getConfigByName("webUploadpath");
        String filename=saveImg(imgfile,savaPath);

        message=filename;
        j.setMsg(message);
        return j;
    }

    /**
     * 二维码识别
     * @param imgfile
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(params ="QR_Droid")
    public AjaxJson QR_Droid(String imgfile, HttpServletRequest request)  throws IOException{
        String message = "";
        AjaxJson j = new AjaxJson();
//        String savaPath=request.getRealPath("/upload/QR");//ResourceUtil.getConfigByName("webUploadpath");
        String savaPath= ResourceUtil.getConfigByName("webUploadpath");
//        String fileallpath=saveImg(imgfile,savaPath);
        System.out.print("savaPath"+savaPath);
        System.out.print("imgfile"+imgfile);
        message=QR_Decode(savaPath+"/"+imgfile);
        j.setMsg(message);
        System.out.print("message"+message);
        return j;
    }

    /**
     * 将base64图片保存到指定路径，返回完整路径
     * @param imgfile
     * @param filepath
     * @return
     * @throws IOException
     */
    public String saveImg(String imgfile,String filepath)throws IOException{
        BASE64Decoder decoder = new BASE64Decoder();
        // 获得一个图片文件流，我这里是从flex中传过来的
        byte[] result = decoder.decodeBuffer(imgfile.split(",")[1]);//解码
        try {
            for (int i = 0; i < result.length; ++i) {
                if (result[i] < 0) {// 调整异常数据
                    result[i] += 256;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 生成文件名
        String nowday=new SimpleDateFormat("yyyyMMdd").format(new Date());
        String files =  new SimpleDateFormat("yyyyMMddHHmmssSSS")
                .format(new Date())
                + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000)
                + ".png";
        // 生成文件路径
//        String ctxPath=ResourceUtil.getConfigByName("webUploadpath")+"/"+nowday;
        String ctxPath=filepath+"/"+nowday;

        File file = new File(ctxPath);
        if (!file.exists()) {
            file.mkdirs();// 创建文件根目录
        }
        String imgPath= nowday+"/"+files;
        String savePath=ctxPath+"/"+files;

        try {
            // 生成文件
            File imageFile = new File(savePath);
            imageFile.createNewFile();
            if(!imageFile.exists()){
                imageFile.createNewFile();
            }
            OutputStream imageStream = new FileOutputStream(imageFile);
            imageStream.write(result);
            imageStream.flush();
            imageStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imgPath;
    }

    /**
     * 二维码识别
     * @param filePath
     * @return
     * @throws IOException
     */
    public String QR_Decode(String filePath){
        String qr_result="";
        BufferedImage image;
        try {
            image = ImageIO.read(new File(filePath));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result=new MultiFormatReader().decode(binaryBitmap,hints); // 对图像进行解码
            //JSONObject content = JSONObject.parseObject(result.getText());
            qr_result= result.getText();//content.getString("zxing");
        } catch (IOException e) {
            e.printStackTrace();
        }catch (NotFoundException e) {
            e.printStackTrace();
        }
        return qr_result;
    }


}
